﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WCYCReader.Models;
using WCYCReader.Utility;
using WCYCReader.Utility.SocketHelper;
using WCYCReader.ViewModels;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;

namespace WCYCReader.Pages
{
    public partial class BookImportPage : PhoneApplicationPage
    {
        // PC 端服务器的地址
        string remoteIP = "192.168.1.108";//默认电脑IP地址
        int remotePort = 8888;//默认端口
        SocketClient socketClient;

        public BookImportPage()
        {
            InitializeComponent();
            this.AddHeaderToPivotItem();
            //
            MyIPAddress finder = new MyIPAddress();
            finder.Find((address) =>
            {
                Dispatcher.BeginInvoke(() =>
                {
                    this.txtPhoneIp.Text = "手机IP地址：" + (address == null ? "Unknown" : address.ToString());
                });
            });

            this.txtRemoteIp.Text = this.remoteIP;
            this.txtRemotePort.Text = this.remotePort.ToString();
            socketClient = new SocketClient();
            socketClient.Completed += client_Completed;
        }

        private void AddHeaderToPivotItem()
        {
            //<TextBlock Margin="-20,-15,0,0" Foreground="#c1dc23" FontSize="60" Text="详细信息"/>
            //this.piAll.Header = new PivotItemHelper().CreateTextBlock("书城综合榜");
            this.piUploadFile.Header = new PivotItemHelper().CreateTextBlock("连接电脑");
            this.piImport.Header = new PivotItemHelper().CreateTextBlock("导入书架");
            this.piHelp.Header = new PivotItemHelper().CreateTextBlock("使用帮助");
        }

        void client_Completed(object sender, string e)
        {
            ShowMsg(e);
        }

        void ShowMsg(string strMsg)
        {
            this.Dispatcher.BeginInvoke(delegate
            {
                this.txtInfo.Text += string.Concat(strMsg, Environment.NewLine);

                // 滚动到底部
                scroll.ScrollToVerticalOffset(scroll.VerticalOffset);
            });
        }



        private void btnImport_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //FileOpenPicker openPicker = new FileOpenPicker();
            //openPicker.ViewMode = PickerViewMode.Thumbnail;
            //openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            //openPicker.FileTypeFilter.Add(".txt");
            try
            {
                socketClient.Connect(this.txtRemoteIp.Text.Trim(), Convert.ToInt32(this.txtRemotePort.Text.Trim()));
                ShowMsg("正在连接服务器....");
            }
            catch (Exception err)
            {
                ShowMsg(err.Message);
            }
        }

        private void btnSendToRemote_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            string sendInfo = this.txtSendInfo.Text.Trim();
            if (!string.IsNullOrEmpty(sendInfo))
            {
                socketClient.Send(new DataType { IsFile = false }, null, sendInfo);
                ShowMsg(sendInfo);
                this.txtSendInfo.Text = string.Empty;
            }
            else
            {
                ShowMsg("请先输入内容");
            }
        }

        private async void btnScanFiles_Click(object sender, RoutedEventArgs e)
        {
            IReadOnlyList<Windows.Storage.StorageFile> files = await CommonHelper.ScanFiles();
            if (files != null && files.Count > 0)
            {
                System.Collections.ObjectModel.ObservableCollection<StorageFile> items = new System.Collections.ObjectModel.ObservableCollection<StorageFile>();
                foreach (StorageFile file in files)
                {
                    items.Add(file);
                }
                this.llsUploadBooks.ItemsSource = items;
            }
            else
            {
                MessageBox.Show("该文件夹中没有文件");
            }
        }

        private void TextBlock_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.pivot.SelectedItem = this.piHelp;
        }

        private void miImport_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }

        private async void btnImportBookStore_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            StorageFile file = this.llsUploadBooks.SelectedItem as StorageFile;
            if (file == null)
            {
                //
                return;
            }

            try
            {
                //读取文件
                // 获取应用程序数据存储文件夹
                StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
                StorageFolder applicationFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(CommonHelper.FolderName, CreationCollisionOption.OpenIfExists);

                StorageFile storageFile = null;

                try
                {
                    // 在指定的应用程序数据存储文件夹中查找指定的文件
                    storageFile = await applicationFolder.GetFileAsync(file.Name);
                }
                catch (System.IO.FileNotFoundException ex)
                {
                    // 没找到指定的文件
                    //lblMsg.Text = "没有找到对应的文件";
                }

                string fileContent = string.Empty;
                // 获取指定的文件的文本内容
                if (storageFile != null)
                {
                    IRandomAccessStreamWithContentType accessStream = await storageFile.OpenReadAsync();

                    using (Stream stream = accessStream.AsStreamForRead((int)accessStream.Size))
                    {
                        byte[] content = new byte[stream.Length];
                        await stream.ReadAsync(content, 0, (int)stream.Length);
                        fileContent = Encoding.UTF8.GetString(content, 0, content.Length);
                    }
                }
                //写入文件
                if (!string.IsNullOrWhiteSpace(fileContent))
                {
                    using (IsolatedStorageFileStream isolatedStorageFileStream = App.QQReader_StorageFile.StorageFile.OpenFile(file.Name, FileMode.Create, FileAccess.ReadWrite))
                    {
                        using (StreamWriter sw = new StreamWriter(isolatedStorageFileStream))
                        {
                            sw.Write(fileContent);
                            sw.Close();
                        }
                    }

                    //添加至书架
                    //BookList_M bookList = new BookList_M ();
                    //new LocalBookList_VM().AddBookList(bookList);
                    
                    //
                    //int localBookListIndex1 = -1;
                    //for (int i = 0; i < App.LocalBook.T_LocalBookListViewModel().Count; i++)
                    //{
                    //    //if (App.LocalBook.T_LocalBookList_VM1()[i].str_Id_M == id)
                    //    if (App.LocalBook.T_LocalBookListViewModel()[i].str_Id_M == file.Name)
                    //    {
                    //        localBookListIndex1= i;
                    //    }
                    //}                    
                    //if (localBookListIndex1 != -1)
                    //{
                    //    //                        App.LocalBook.T_LocalBookList_VM1()[localBookListIndex1].int_IsDownload_M = 2;
                    //    App.LocalBook.T_LocalBookListViewModel()[localBookListIndex1].int_IsDownload_M = 2;
                    //}
                    //else
                    //{
                    //    localBookListIndex1 = -1;
                    //    for (int i = 0; i < App.LocalBook.T_LocalBookListViewModel().Count; i++)
                    //    {
                    //        //if (App.LocalBook.T_LocalBookList_VM2()[i].str_Id_M == id)
                    //        if (App.LocalBook.T_LocalBookListViewModel()[i].str_Id_M == file.Name)
                    //        {
                    //            localBookListIndex1= i;
                    //        }
                    //    }
                    //    //App.LocalBook.T_LocalBookList_VM2()[localBookListIndex1].int_IsDownload_M = 2;
                    //    App.LocalBook.T_LocalBookListViewModel()[localBookListIndex1].int_IsDownload_M = 2;
                    //}                    
                }


            }
            catch
            { }
        }


    }
}